<template>
  <div>

    <el-card class="box-card">
      <el-button v-has="`btn.Trademark.add`" type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
      <el-table class="table" style="margin:10px 0px;" :border="true" :data="trademarkArr">
        <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <!-- <template #="{ row, $index }"> -->
          <template #="{ row }">
            <img :src="row.logoUrl" style="width: 50px;height: 50px;">
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button type="warning" size="small" icon="Edit" @click="updateTrademark(row)"></el-button>
            <el-popconfirm :title="`您确定要删除${row.tmName}?`" width="250px" icon="Delete" @confirm='removeTradeMark(row.id)'>
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="sizeChange" @current-change="getHasTrademark" :pager-count="9"
        v-model:current-page="page.pageNo" v-model:page-size="page.limit" :page-sizes="[3, 5, 7, 9]" :background="true"
        layout="prev, pager, next, jumper,->,sizes,total" :total="page.total" />
    </el-card>
    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
      <el-form style="width: 80%;" :model="trademarkParams" ref="formRef">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, UploadProps } from 'element-plus'
import { onMounted, reactive, ref } from 'vue';
import type { pageType } from '@/views/type'
import { reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import type { Records, TradeMarkResponseData, TradeMark } from '@/api/product/type'

const page = reactive<pageType>({
  pageNo: 1,
  limit: 3,
  total: 0
})
onMounted(() => {
  getHasTrademark()
})
// 表格数据
let trademarkArr = ref<Records>([]);
// 对话框显示与否
let dialogFormVisible = ref<boolean>(false)
// 定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
// 添加品牌
const addTrademark = () => {
  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
}
// 修改品牌
const updateTrademark = (row: TradeMark) => {
  // nextTick(() => {
  //   formRef.value.clearValidate('tmName');
  //   formRef.value.clearValidate('logoUrl');
  // })
  dialogFormVisible.value = true
  Object.assign(trademarkParams, row)
}
// 删除
const removeTradeMark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    ElMessage.success('删除品牌成功')
    getHasTrademark(trademarkArr.value.length > 1 ? page.pageNo : page.pageNo - 1);
  } else {
    ElMessage.error('删除品牌失败')
  }
}
let formRef = ref();
// 图片上传前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage.error('上传文件大小小于4M')
      return false;
    }
  } else {
    ElMessage.error('上传文件格式务必PNG|JPG|GIF')
    return false;
  }
}
// 图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: any) => {
  trademarkParams.logoUrl = response.data;
  formRef.value.clearValidate('logoUrl');
}
const cancel = () => {
  dialogFormVisible.value = false
}
const confirm = async () => {
  // console.log('trademarkParams',trademarkParams)
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  //添加|修改已有品牌
  if (result.code == 200) {
    dialogFormVisible.value = false
    ElMessage.success(trademarkParams.id ? '修改品牌成功' : '添加品牌成功')
    getHasTrademark(trademarkParams.id ? page.pageNo : 1);
  } else {
    ElMessage.error(trademarkParams.id ? '修改品牌失败' : '添加品牌失败')
    dialogFormVisible.value = false
  }
}
// 获取已有品牌
const getHasTrademark = async (pager = 1) => {
  //当前页码
  page.pageNo = pager
  let result: TradeMarkResponseData = await reqHasTrademark(page.pageNo, page.limit)
  // console.log('result', result)
  if (result.code == 200) {
    page.total = result.data.total
    trademarkArr.value = result.data.records
  }
}
// 当前每一页的数据量发生变化的时候，当前页码归1
const sizeChange = () => {
  getHasTrademark();
}
// //表单校验规则对象
// const rules = {
//   tmName: [
//     { required: true, trigger: 'blur', validator: validatorTmName }
//   ],
//   logoUrl: [
//     { required: true, validator: validatorLogoUrl }
//   ]
// }
// // 品牌自定义校验规则方法
// const validatorTmName = (rule: any, value: any, callBack: any) => {
//   if (value.trim().length >= 2) {
//     callBack();
//   } else {
//     callBack(new Error('品牌名称位数大于等于两位'))
//   }
// }
// //品牌LOGO图片的自定义校验规则方法
// const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
//   if (value) {
//     callBack();
//   } else {
//     callBack(new Error('LOGO图片务必上传'))
//   }
// }
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>